<?php namespace App\Services\UserCollectionsService;
/**
 * 用户作品集
 *
 * 用户作品集service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
use App\Services\BaseService;
use App\Services\ImgServices\ImgTool;
use App\Services\UserService\UserTool;
use App\Services\Tool\GeneralTool;
use App\Services\ProductsService\ProductTool;
use App\Services\Exceptions\UserConllectionNotFoundException;
use Log;

class UserCollectionsService extends BaseService{

    protected $imgTool;
    protected $userTool;
    protected $tool;
    protected $product_tool;
    public function __construct(ImgTool $imgTool,UserTool $userTool,GeneralTool $tool,ProductTool $product_tool)
    {
        $this->imgTool = $imgTool;
        $this->userTool = $userTool;
        $this->tool = $tool;
        $this->product_tool = $product_tool;
    }

    public function get_collection_by_user_id_collection_id($user_id,$collection_id){
        $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$user_id),array('collection_id','=',$collection_id),array('state','=',1)),'select'=>array('collection_name','original_image','thumbnail','is_default')));
        $user_collection = $this->getById();
        return $user_collection;
    }

    /**
     * 创建作品集
     * @param $input
     * @return array
     */
    public function createUserCollection($input){
        $check_result = $this->checkParams($input);
        if($check_result !== true){
            return $check_result;
        }
        //保存作品封面
        $is_original_image_valid = ImgTool::imageUrlIsValid($input['original_image']);
        $is_thumbnail_valid = ImgTool::imageUrlIsValid($input['thumbnail']);
        if($is_original_image_valid == false || $is_thumbnail_valid == false){
            return $this->createResult('M09030',(object)array());
        }
        $input['original_image'] = ImgTool::getImgPathByImgUrl($input['original_image']);
        $input['thumbnail'] = ImgTool::getImgPathByImgUrl($input['thumbnail']);
        //$input['thumbnail'] = $this->imgTool->getImgThumbByImgPath($input['original_image'],170,170);
        $input['collection_name'] = $this->tool->removeEmoji($input['collection_name']);
        $input['collection_id'] = $this->tool->only_no();
        $input['created_at'] = $input['updated_at'] = time();
        $this->table = 'user_collections';
        $result = $this->save($input);
        return empty($result) ? $this->createResult('M00003',(object)array()) :
            $this->createResult('M00000',array('collection_id'=>$input['collection_id'],'collection_name'=>$input['collection_name'],'original_image'=>env('IMG_URL_STD_PREFIX').$input['original_image'], 'thumbnail'=>env('IMG_URL_STD_PREFIX').$input['thumbnail'],'is_default'=>0),'','作品集已创建',0);
    }

    /**
     * 更新
     * @param $input
     * @return array|bool
     */
    public function updateUserCollection($input){
        $check_result = $this->checkParams($input);
        if($check_result !== true){
            return $check_result;
        }
        //获取collection_id
        $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$input['user_id']),array('collection_id','=',$input['collection_id']),array('state','=',1)),'select'=>array('collection_name','original_image','thumbnail','is_default')));
        $user_collection = $this->getById();
        if(empty($user_collection)){
            return $this->createResult('M09034',(object)array());
        }
        //保存作品封面
        $is_original_image_valid = ImgTool::imageUrlIsValid($input['original_image']);
        $is_thumbnail_valid = ImgTool::imageUrlIsValid($input['thumbnail']);
        if($is_original_image_valid == false || $is_thumbnail_valid == false){
            return $this->createResult('M09030',(object)array());
        }
        $input['original_image'] = ImgTool::getImgPathByImgUrl($input['original_image']);
        $input['thumbnail'] = ImgTool::getImgPathByImgUrl($input['thumbnail']);
        if($input['original_image'] == $user_collection->original_image){
            unset($input['original_image']);
            unset($input['thumbnail']);
        }
        if($user_collection->is_default == 1){
            unset($input['collection_name']);
        }else{
            $input['collection_name'] = $this->tool->removeEmoji($input['collection_name']);
        }
        $input['updated_at'] = time();
        $this->table = 'user_collections';
        $this->where = array(array('collection_id','=',$input['collection_id']));
        $result = $this->update($input);
        return empty($result) ? $this->createResult('M00003',(object)array()) :
            $this->createResult('M00000',(object)array(),'','作品集已修改',0);

    }

    /**
     * 检查参数
     * @param $input
     * @return array|bool
     */
    private function checkParams($input){
        $is_user = $this->userTool->isUser($input['user_id']);
        if($is_user == false){
            return $this->createResult('M09005',(object)array());
        }
        $code = $this->tool->getcode($input['collection_name']);
        if($code == false){
            $this->createResult('M09031',(object)array());
        }
        if(isset($input['collection_id'])){
            $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$input['user_id']),array('collection_name','=',$input['collection_name']),array('collection_id','<>',$input['collection_id']),array('state','=',1))));
        }else{
            $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$input['user_id']),array('collection_name','=',$input['collection_name']),array('state','=',1))));
        }
        $userCollections = $this->count();
        if($userCollections > 0){
            return $this->createResult('M09032',(object)array());
        }
        return true;
    }

    /**
     * 获取作品集列表
     * @param $user_id
     * @param int $per_page
     * @return array
     */
    public function getList($user_id,$per_page=10){
        $this->setParameter(array(
            'table'=>'user_collections',
            'where'=>array(
                array('user_id','=',$user_id),array('state','=',1)
            ),
            'select'=>array('collection_id','collection_name','original_image', 'thumbnail','is_default'),
            'order'=>'created_at',
            'sort'=>'asc'
        ));
        $user_collections = $this->getAllPaginated($per_page)->toArray();
//        usort($user_collections['data'], function($a, $b) {
//            $al = $a->is_default;
//            $bl = $b->is_default;
//            if ($al == $bl)
//                return 0;
//            return ($al < $bl) ? 1 : -1;
//        });
        foreach($user_collections['data'] as $collection){
            $collection->original_image = $this->setImagePath($collection->original_image);
            $collection->thumbnail = $this->setImagePath($collection->thumbnail);
            $collection->create_quantity = $this->product_tool->get_collection_create_quantity($user_id,$collection->collection_id);
        }
        $result = array('total_page'=>$user_collections['last_page'],'per_page'=>$per_page,'current_page'=>$user_collections['current_page'],'data'=>$user_collections['data']);
        return $this->createResult('M00000',$result);
    }



    /**
     * 部分页获取用户作品集（productService）
     * @param $user_id
     * @return array
     */
    public function getListNoPaginated($user_id){
        $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$user_id),array('state','=',1)),'select'=>array('collection_id','collection_name','original_image','thumbnail','is_default'),'order'=>'created_at','sort'=>'asc'));
        $user_collections = $this->getAll()->toArray();
        foreach($user_collections as $collection){
            $collection->original_image = $this->setImagePath($collection->original_image);
            $collection->thumbnail = $this->setImagePath($collection->thumbnail);
        }
        $result = array('type'=>0,'data'=>$user_collections);
        return $this->createResult('M00000',$result);
    }

    /**
     * 删除
     * @param $user_id
     * @param $collection_id
     * @return array
     */
    public function deleteCollection($user_id,$collection_id){
        try{
            $this->setParameter(array('table'=>'user_collections','where'=>array(array('user_id','=',$user_id),array('collection_id','=',$collection_id),array('state','=',1)),'select'=>array('collection_name','original_image','thumbnail','is_default')));
            $user_collection = $this->getById();
            if(empty($user_collection)){
                return $this->createResult('M00000',(object)array());
            }
            if($user_collection->is_default == 1){
                return $this->createResult('M09035',(object)array());
            }
            $input = array('state'=>2,'updated_at'=>time());
            $this->table = 'user_collections';
            $this->where = array(array('collection_id','=',$collection_id));
            $result = $this->update($input);
            if(empty($result)){
                return $this->createResult('M09038',(object)array());
            }else{
                //获取该用户的默认作品集
                $this->setParameter([
                    'table' => 'user_collections',
                    'where' => [['user_id','=',$user_id],['is_default','=',1],['state','=',1]],
                    'select'=>'collection_id'
                ]);
                $user_collection = $this->getById();
                if(empty($user_collection)){
                    throw new UserConllectionNotFoundException('ID为'.$user_id.'的用户没有默认作品集');
                }
                $this->product_tool->transfer_to_default_collection($user_id,$collection_id,$user_collection->collection_id);
                return $this->createResult('M00000',(object)array(),'globalcodes','删除');
            }
        }catch (\Exception $e){
            Log::info($e);
            return $this->createResult('M00000',(object)array());
        }
    }
}
